package com.xsomnus.algorithm.common;

import java.util.LinkedList;
import java.util.List;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019/7/19 0019 13:59
 * - 才需学也,学需静也/非淡泊无以明志，非宁静无以致远
 */
public class RedPacket {

    private static final int MIN_MONEY = 1;
    private static final int MAX_MONEY = 20000;
    private static final double TIMES = 2.1F;
    /**
     * 小于最小值
     */
    private static final int LESS = -1;
    /**
     * 大于最大值
     */
    private static final int MORE = -2;

    /**
     * 正常值
     */
    private static final int OK = 1;

    private int recursiveCount = 0;


    public List<Integer> splitRedPacket(int money, int count) {
        List<Integer> moneys = new LinkedList<>();

        //单个红包的最大金额
        int max = (int) ((money / count) * TIMES);
        max = max > MAX_MONEY ? MAX_MONEY : max;

        for (int i = 0; i < count; i++) {
            int redPacket = randomRedPacket(money, MIN_MONEY, max, count - i);
            moneys.add(redPacket);
            money -= redPacket;
        }
        return moneys;
    }

    /**
     * @param totalMoney 总金额
     * @param min       最小金额
     * @param max       最大金额
     * @param count     数量
     * @return 返回红包的金额
     */
    private int randomRedPacket(int totalMoney, int min, int max, int count) {
        if (count == 1) {
            return totalMoney;
        }
        if (min == max) {
            return min;
        }

        max = max > totalMoney ? totalMoney : max;

        int redPacket = (int)(Math.random() * (max - min) + min);
        int leftMoney = totalMoney - redPacket;

        int status = checkMoney(leftMoney, count - 1);
        if (OK == status) {
            return redPacket;
        }

        if (LESS == status) {
            recursiveCount++;
            System.out.println("recursiveCount==" + recursiveCount);
            return randomRedPacket(totalMoney, min, redPacket, count);
        }

        if (MORE == status) {
            recursiveCount++;
            System.out.println("recursiveCount==" + recursiveCount);
            return randomRedPacket(totalMoney, redPacket, max, count);
        }

        return 0;
    }

    private int checkMoney(int leftMoney, int count) {
        double avg = leftMoney / count;
        if (avg < MIN_MONEY) {
            return LESS;
        }
        if (avg > MAX_MONEY) {
            return MORE;
        }
        return OK;
    }
}
